import logging
import traceback
import time
from flask import jsonify
from dao.db_connect import db_connect as db
from datetime import date, timedelta


internal_error = 500  # 服务器错误
success = 200  # 请求成功
data_missing = 101  # 数据库内无相关数据
identification_error = 100  # 未识别成功

EXCHANGE_START_DATE = '2020-6-1'
EXCHANGE_END_DATE = '2021-6-1'
EMISSION_START_DATE = '2020-9-30'
EMISSION_END_DATE = '2021-9-30'

country_list = ['Brazil', 'China', 'EU27 & UK', 'France',
                'Germany', 'India', 'Italy', 'Japan',
                'ROW', 'Russia', 'Spain', 'UK', 'US', 'WORLD'
                ]
emission_categorys = [
    'Total', 'Power', 'Industry', 'Ground Transport',
    'Residential', 'Domestic Aviation', 'International Aviation'
]
emission_dic = {
    'Total': 'Total',
    'Power': 'Power',
    'Industry': 'Industry',
    'Residential': 'Residential',
    'Ground Transport': 'Ground_Transport',
    'Domestic Aviation': 'Domestic_Aviation',
    'International Aviation': 'International_Aviation'
}

exchange_categorys = [
    '北京', '上海', '福建', '广东',
    '湖北', '深圳', '天津', '重庆'
]
exchange_dic = {
    '北京': 'Beijing', '上海': 'Shanghai',
    '福建': 'Fujian', '广东': 'Guangdong',
    '湖北': 'Hubei', '深圳': 'Shenzhen',
    '天津': 'Tianjin', '重庆': 'Chongqin'
}

exchange_cache = {}
CACHE_EXPIRE_TIME = 3600
emission_cache = {}


class GetImagesData(object):

    @classmethod
    def get_carbon_emission(cls, request):
        """
        获取碳排放数据
        dateArray:日期列表
        emissionArray:排放列表
        """
        logging.debug("working on get_carbon_emission")
        msg = "获取排放数据列表成功"
        code = success

        country = request.values.get('country')
        start_date = request.values.get('startdate')
        end_date = request.values.get('enddate')

        if start_date is None or len(start_date) == 0:
            start_date = EMISSION_START_DATE
        if end_date is None or len(end_date) == 0:
            end_date = EMISSION_END_DATE

        try:
            if start_date == EMISSION_START_DATE and end_date == EMISSION_END_DATE:
                emission_data = emission_cache.get(country)
                current_time = int(time.time())
                if emission_data is None or current_time - emission_data["time"] > CACHE_EXPIRE_TIME:
                    logging.info(str(country) + ": emission_cache update")
                    start_date = EMISSION_START_DATE
                    end_date = EMISSION_END_DATE

                    sql_data = {}
                    for sector in emission_categorys:
                        query_sql = f'select date_time, co2 from country_emission ' \
                                    f'where country = "{country}" and sector = "{sector}" ' \
                                    f'and date_time >= "{start_date}" and date_time <= "{end_date}" ' \
                                    f'order by date_time'
                        data = db.queryAll(query_sql)
                        date_list = []
                        co2_list = []
                        for dic_data in data:
                            date_list.append(dic_data['date_time'].strftime('%Y-%m-%d'))
                            co2_list.append(float(dic_data['co2']))
                        sql_data[emission_dic[sector]] = {
                            "dateArray": date_list,
                            "emissionArray": co2_list
                        }
                    emission_data = {
                        "data": sql_data,
                        "time": current_time
                    }
                    emission_cache[country] = emission_data

                sql_data = emission_data["data"]
                return jsonify(code=code, data=sql_data, msg=msg)

            sql_data = {}
            for sector in emission_categorys:
                query_sql = f'select date_time, co2 from country_emission ' \
                            f'where country = "{country}" and sector = "{sector}" ' \
                            f'and date_time >= "{start_date}" and date_time <= "{end_date}" ' \
                            f'order by date_time'
                data = db.queryAll(query_sql)
                date_list = []
                co2_list = []
                for dic_data in data:
                    date_list.append(dic_data['date_time'].strftime('%Y-%m-%d'))
                    co2_list.append(float(dic_data['co2']))
                sql_data[emission_dic[sector]] = {
                    "dateArray": date_list,
                    "emissionArray": co2_list
                }
        except Exception as e:
            msg = "获取排放数据列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())
            return jsonify(code=code, data={}, msg=msg)
        return jsonify(code=code, data=sql_data, msg=msg)

    @classmethod
    def get_carbon_exchange(cls, request):
        """
        获取交易数据
        dateArray:日期列表
        priceArray:价格列表
        amountArray:交易量列表
        """
        logging.debug("working on get_exchange_data")
        code = success
        msg = "获取交易数据列表成功"
        date_list = []
        price_list = []
        amount_list = []

        exchange = request.values.get('exchange')
        start_date = request.values.get('startdate')
        end_date = request.values.get('enddate')
        if start_date is None or len(start_date) == 0:
            start_date = EXCHANGE_START_DATE
        if end_date is None or len(end_date) == 0:
            end_date = EXCHANGE_END_DATE

        try:
            if start_date == EXCHANGE_START_DATE and end_date == EXCHANGE_END_DATE:
                exchange_data = exchange_cache.get(exchange)
                current_time = int(time.time())
                if exchange_data is None or current_time - exchange_data["time"] > CACHE_EXPIRE_TIME:
                    logging.info(str(exchange) + ": exchange_cache update")
                    start_date = EXCHANGE_START_DATE
                    end_date = EXCHANGE_END_DATE

                    query_sql = f'select date_time, final_price, trading_ton, exchange_type from exchange_data ' \
                                f'where city = "{exchange}" and date_time >= "{start_date}" ' \
                                f'and date_time <= "{end_date}" order by date_time'
                    data = db.queryAll(query_sql)
                    date_list = []
                    price_list = []
                    amount_list = []
                    for dic_data in data:
                        if exchange == '深圳' and dic_data['exchange_type'] != 'SZA-2013':
                            continue
                        date_list.append(dic_data['date_time'].strftime('%Y-%m-%d'))
                        price_list.append(float(dic_data['final_price']))
                        amount_list.append(float(dic_data['trading_ton']))

                    exchange_data = {
                        "data": {
                            "dateArray": date_list,
                            "priceArray": price_list,
                            "amountArray": amount_list
                        },
                        "time": current_time
                    }
                    exchange_cache[exchange] = exchange_data

                sql_data = exchange_data["data"]
                return jsonify(code=code, data=sql_data, msg=msg)

            query_sql = f'select date_time, final_price, trading_ton, exchange_type from exchange_data ' \
                        f'where city = "{exchange}" and date_time >= "{start_date}" and date_time <= "{end_date}"' \
                        f'order by date_time'
            data = db.queryAll(query_sql)
            for dic_data in data:
                if exchange == '深圳' and dic_data['exchange_type'] != 'SZA-2013':
                    continue
                date_list.append(dic_data['date_time'].strftime('%Y-%m-%d'))
                price_list.append(float(dic_data['final_price']))
                amount_list.append(float(dic_data['trading_ton']))

        except Exception as e:
            msg = "获取交易数据列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())
            return jsonify(code=code, data={}, msg=msg)

        resp = {
            "code": code,
            "msg": msg,
            "data": {
                "dateArray": date_list,
                "priceArray": price_list,
                "amountArray": amount_list
            }
        }
        return jsonify(resp)

    @classmethod
    def get_carbon_exchange_all(cls, request):
        """
        获取所有交易数据
        dateArray:日期列表
        priceArray:价格列表
        amountArray:交易量列表
        """
        logging.debug("working on get_exchange_data")
        code = success
        msg = "获取交易数据列表成功"
        start_date = request.values.get('startdate')
        end_date = request.values.get('enddate')
        if start_date is None or len(start_date) == 0:
            start_date = EXCHANGE_START_DATE
        if end_date is None or len(end_date) == 0:
            end_date = EXCHANGE_END_DATE

        sql_data = {}
        try:
            if start_date == EXCHANGE_START_DATE and end_date == EXCHANGE_END_DATE:
                for exchange in exchange_categorys:
                    exchange_data = exchange_cache.get(exchange)
                    current_time = int(time.time())
                    if exchange_data is None or current_time - exchange_data["time"] > CACHE_EXPIRE_TIME:
                        logging.info(str(exchange) + ": exchange_cache update")
                        start_date = EXCHANGE_START_DATE
                        end_date = EXCHANGE_END_DATE

                        query_sql = f'select date_time, final_price, trading_ton, exchange_type from exchange_data ' \
                                    f'where city = "{exchange}" and date_time >= "{start_date}" ' \
                                    f'and date_time <= "{end_date}" order by date_time'
                        data = db.queryAll(query_sql)
                        date_list = []
                        price_list = []
                        amount_list = []
                        for dic_data in data:
                            if exchange == '深圳' and dic_data['exchange_type'] != 'SZA-2013':
                                continue
                            date_list.append(dic_data['date_time'].strftime('%Y-%m-%d'))
                            price_list.append(float(dic_data['final_price']))
                            amount_list.append(float(dic_data['trading_ton']))

                        exchange_data = {
                            "data": {
                                "dateArray": date_list,
                                "priceArray": price_list,
                                "amountArray": amount_list
                            },
                            "time": current_time
                        }
                        exchange_cache[exchange] = exchange_data
                    sql_data[exchange_dic[exchange]] = exchange_data["data"]
                return jsonify(code=code, data=sql_data, msg=msg)

            for exchange in exchange_categorys:
                query_sql = f'select date_time, final_price, trading_ton, exchange_type from exchange_data ' \
                            f'where city = "{exchange}" and date_time >= "{start_date}" and date_time <= "{end_date}"' \
                            f'order by date_time'
                data = db.queryAll(query_sql)
                date_list = []
                price_list = []
                amount_list = []
                for dic_data in data:
                    if exchange == '深圳' and dic_data['exchange_type'] != 'SZA-2013':
                        continue
                    date_list.append(dic_data['date_time'].strftime('%Y-%m-%d'))
                    price_list.append(float(dic_data['final_price']))
                    amount_list.append(float(dic_data['trading_ton']))
                sql_data[exchange_dic[exchange]] = {
                    "dateArray": date_list,
                    "priceArray": price_list,
                    "amountArray": amount_list
                }
        except Exception as e:
            msg = "获取交易数据列表失败"
            code = data_missing
            logging.debug(traceback.format_exc())
            return jsonify(code=code, data={}, msg=msg)

        return jsonify(code=code, data=sql_data, msg=msg)
